from typing import List, Optional
from pydantic import BaseModel, Field, field_validator
from datetime import datetime

class RouteBase(BaseModel):
    route_id: str = Field(..., min_length=1, max_length=20, description="线路编号")
    name: str = Field(..., min_length=1, max_length=100, description="线路名称")
    start_station: str = Field(..., min_length=1, max_length=100, description="起始站")
    end_station: str = Field(..., min_length=1, max_length=100, description="终点站")
    stops: List[str] = Field(default_factory=list, description="途经站点")
    distance_km: float = Field(..., gt=0, description="全程里程(公里)")
    estimated_time: int = Field(..., gt=0, description="预计耗时(分钟)")
    operational_hours: str = Field(..., pattern=r'^([0-1][0-9]|2[0-3]):[0-5][0-9]-([0-1][0-9]|2[0-3]):[0-5][0-9]$', description="运营时间段")
    base_price: float = Field(..., gt=0, description="基础票价")
    status: str = Field(..., pattern='^(active|maintenance|closed)$', description="运营状态")
    
    @field_validator('stops')
    @classmethod
    def validate_stops(cls, v):
        if not v:
            raise ValueError("途经站点不能为空")
        return v

class RouteCreate(RouteBase):
    max_capacity: int = Field(..., gt=0, description="单日最大班次数")
    emergency_contact: Optional[str] = Field(None, max_length=20, description="紧急联系电话")
    notes: Optional[str] = Field(None, description="内部备注")

class RouteUpdate(BaseModel):
    name: Optional[str] = Field(None, min_length=1, max_length=100, description="线路名称")
    stops: Optional[List[str]] = Field(None, description="途经站点")
    distance_km: Optional[float] = Field(None, gt=0, description="全程里程(公里)")
    estimated_time: Optional[int] = Field(None, gt=0, description="预计耗时(分钟)")
    operational_hours: Optional[str] = Field(None, pattern=r'^([0-1][0-9]|2[0-3]):[0-5][0-9]-([0-1][0-9]|2[0-3]):[0-5][0-9]$', description="运营时间段")
    base_price: Optional[float] = Field(None, gt=0, description="基础票价")
    status: Optional[str] = Field(None, pattern='^(active|maintenance|closed)$', description="运营状态")
    max_capacity: Optional[int] = Field(None, gt=0, description="单日最大班次数")
    emergency_contact: Optional[str] = Field(None, max_length=20, description="紧急联系电话")
    notes: Optional[str] = Field(None, description="内部备注")

class RouteResponse(RouteBase):
    id: int
    max_capacity: int
    emergency_contact: Optional[str]
    notes: Optional[str]
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True

class RoutePublicResponse(BaseModel):
    route_id: str
    name: str
    start_station: str
    end_station: str
    stops: List[str]
    distance_km: float
    estimated_time: int
    operational_hours: str
    base_price: float
    status: str
    
    class Config:
        from_attributes = True 